//
//  RegisterViewController.m
//  zhuchiren
//
//  Created by rainday on 15/1/10.
//  Copyright (c) 2015年 rainday. All rights reserved.
//

#import "RegisterViewController.h"
#import <ReactiveCocoa.h>
#import <RACEXTScope.h>
#import <SMS_SDK/SMS_SDK.h>
#import "LoginViewModel.h"
#import "NetErrorStateCode.h"


@interface RegisterViewController ()<UITextFieldDelegate>
@property (nonatomic ,weak) IBOutlet UIView *navView;
@property (nonatomic ,weak) IBOutlet UIButton *getVerButton;
@property (nonatomic ,weak) IBOutlet UIButton *registerButton;

@property (nonatomic ,weak) IBOutlet UIButton *manButton;
@property (nonatomic ,weak) IBOutlet UIButton *womanButton;
@property (nonatomic ,weak) IBOutlet UITextField *phoneTextField;
@property (nonatomic ,weak) IBOutlet UITextField *nickNameTextField;
@property (nonatomic ,weak) IBOutlet UITextField *birthdayTextField;
@property (nonatomic ,weak) IBOutlet UITextField *heightTextField;
@property (nonatomic ,weak) IBOutlet UITextField *passwdTextField;
@property (nonatomic ,weak) IBOutlet UITextField *rePasswdTextField;
@property (nonatomic ,weak) IBOutlet UITextField *verTextField;

- (IBAction)dismissSelf:(id)sender;

- (IBAction)selectGender:(id)sender;





@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _getVerButton.layer.cornerRadius = 3.0f;
    _getVerButton.layer.masksToBounds = YES;
    
    _registerButton.layer.cornerRadius = 5.0f;
    _registerButton.layer.masksToBounds = YES;
    
    _navView.layer.shadowColor = [[UIColor colorWithRed:224.0/255 green:79.0/255 blue:95.0/255 alpha:1.0] CGColor];
    _navView.layer.shadowOffset = CGSizeMake(1.0, 1.0);
    _navView.layer.shadowOpacity = .3;
    
    
    [_womanButton setImage:[UIImage imageNamed:@"quanquan"] forState:UIControlStateNormal];
    [_womanButton setImage:[UIImage imageNamed:@"quanquan2"] forState:UIControlStateSelected];
    
    [_manButton setImage:[UIImage imageNamed:@"quanquan"] forState:UIControlStateNormal];
    [_manButton setImage:[UIImage imageNamed:@"quanquan2"] forState:UIControlStateSelected];
    
    _womanButton.selected = YES;
    _manButton.selected = NO;
    
    
    @weakify(self);
    RAC(_getVerButton,enabled) = [RACSignal combineLatest:@[_phoneTextField.rac_textSignal] reduce:^id(NSString *phone){
        return @([phone hasPrefix:@"1"] && [phone length]==11);
        
    }];
    
    RAC(_getVerButton,backgroundColor) = [RACSignal combineLatest:@[_phoneTextField.rac_textSignal] reduce:^id(NSString *phone){
        return [phone hasPrefix:@"1"] && [phone length]==11?[UIColor redColor]:[UIColor lightGrayColor];
        
        
    }];
    
    
    
    [[_getVerButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        [SMS_SDK getVerificationCodeBySMSWithPhone:_phoneTextField.text
                                              zone:@"86"
                                            result:^(SMS_SDKError *error)
         {
             if (!error)
             {
               
                 UIAlertView* alert=[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"发送成功", nil)
                                                               message:@"注意查收"
                                                              delegate:self
                                                     cancelButtonTitle:NSLocalizedString(@"好的", nil)
                                                     otherButtonTitles:nil, nil];
                 [alert show];
                 
             }
             else
             {
                 UIAlertView* alert=[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"codesenderrtitle", nil)
                                                               message:[NSString stringWithFormat:@"状态码：%zi ,错误描述：%@",error.errorCode,error.errorDescription]
                                                              delegate:self
                                                     cancelButtonTitle:NSLocalizedString(@"sure", nil)
                                                     otherButtonTitles:nil, nil];
                 [alert show];
             }
             
         }];

    }];
    
    
    RAC(_registerButton,backgroundColor) = [RACSignal combineLatest:@[_phoneTextField.rac_textSignal,_nickNameTextField.rac_textSignal,_birthdayTextField.rac_textSignal,_heightTextField.rac_textSignal,_passwdTextField.rac_textSignal,_rePasswdTextField.rac_textSignal,_verTextField.rac_textSignal] reduce:^id(NSString *phone,NSString *nickeName,NSString *birthday,NSString *height,NSString *passwd,NSString *rePasswd,NSString *verText){
        
        
        
        return [phone hasPrefix:@"1"] && [phone length]==11 && [nickeName length]>0 && [birthday length]>0 && [height intValue]>130 && [height intValue]<250 && [passwd length]>0 && [passwd isEqualToString:rePasswd] && [verText length]==4?[UIColor redColor]:[UIColor lightGrayColor];
        
        
    }];
    
    RAC(_registerButton,enabled) = [RACSignal combineLatest:@[_phoneTextField.rac_textSignal,_nickNameTextField.rac_textSignal,_birthdayTextField.rac_textSignal,_heightTextField.rac_textSignal,_passwdTextField.rac_textSignal,_rePasswdTextField.rac_textSignal,_verTextField.rac_textSignal] reduce:^id(NSString *phone,NSString *nickeName,NSString *birthday,NSString *height,NSString *passwd,NSString *rePasswd,NSString *verText){
        
        
        
        return @([phone hasPrefix:@"1"] && [phone length]==11 && [nickeName length]>0 && [birthday length]>0 && [height intValue]>130 && [height intValue]<250 && [passwd length]>0 && [passwd isEqualToString:rePasswd] && [verText length]==4);
        
        
        
    }];
    
    
    [[_registerButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
    
        [SMS_SDK commitVerifyCode:_verTextField.text result:^(enum SMS_ResponseState state) {
            if (1==state)
            {
                
                @strongify(self);
                NSString *gender = _womanButton.selected?@"女":@"男";
                [[[LoginViewModel registerPhone:self.phoneTextField.text nickname:_nickNameTextField.text birthday:_birthdayTextField.text height:_heightTextField.text password:_passwdTextField.text gender:gender] subscribeOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(id x) {
                    
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"login" object:nil];
                    [self dismissViewControllerAnimated:YES completion:nil];
                    
                    
                } error:^(NSError *error) {
                    
                    NSString *errorText = [NetErrorStateCode getDescribeText:error];
                    
                    NSString* str=[NSString stringWithFormat:NSLocalizedString(@"注册失败", nil)];
                    UIAlertView* alert=[[UIAlertView alloc] initWithTitle:NSLocalizedString(errorText, nil)
                                                                  message:str
                                                                 delegate:self
                                                        cancelButtonTitle:NSLocalizedString(@"好的", nil)
                                                        otherButtonTitles:nil, nil];
                    [alert show];
                }];
                
                
                
                
            }
            else if(0==state)
            {
                NSString* str=[NSString stringWithFormat:NSLocalizedString(@"verifycodeerrormsg", nil)];
                UIAlertView* alert=[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"verifycodeerrortitle", nil)
                                                              message:str
                                                             delegate:self
                                                    cancelButtonTitle:NSLocalizedString(@"sure", nil)
                                                    otherButtonTitles:nil, nil];
                [alert show];
            }
        }];

    }];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)dismissSelf:(id)sender{
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

- (void)selectGender:(id)sender{
    if ([sender isEqual:_manButton]) {
        _manButton.selected = YES;
        _womanButton.selected = NO;
        
        return;
    }
    _manButton.selected = NO;
    _womanButton.selected = YES;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    
    UIDatePicker *datePicker = [[UIDatePicker alloc] init];
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh-CN"];
    datePicker.locale = locale;
    datePicker.datePickerMode = UIDatePickerModeDate;
    NSTimeZone *zone =[NSTimeZone systemTimeZone];
    datePicker.timeZone = zone;
    
    
    textField.inputView = datePicker;
    
    
    @weakify(self);
    [[datePicker rac_signalForControlEvents:UIControlEventValueChanged] subscribeNext:^(UIDatePicker *datePicker) {
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        
        
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        
        @strongify(self);
        self.birthdayTextField.text = [dateFormatter stringFromDate:datePicker.date];
        
        
    }];
    
    // 建立 UIToolbar
    UIToolbar *toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
    UIBarButtonItem *right = [[UIBarButtonItem alloc]init];
    [right setStyle:UIBarButtonItemStyleDone];
    right.title = NSLocalizedString(@"完成", nil);
    
    right.rac_command = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        [textField resignFirstResponder];
        // An empty signal is a signal that completes immediately.
        return [RACSignal empty];
    }];
    
    
    toolBar.items = [NSArray arrayWithObjects:right,nil];
    textField.inputAccessoryView = toolBar;
    
}




- (void)textFieldDidEndEditing:(UITextField *)textField{
    if ([textField isEqual:_birthdayTextField]) {
        _birthdayTextField.text = textField.text;
    }
}
@end
